package com.sparrow.socket.http.api;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;

/**
 * Http服务启动类
 */
public class HttpServer implements DisposableBean {

    private static Logger logger= LoggerFactory.getLogger(HttpServer.class);
    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap bootstrap;
    private ChannelFuture channelFuture;
    private ChannelInitializer<?> channelInitializer;

    public void start(int port) {
        bootstrap = new ServerBootstrap();
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup(1);
        try {
            bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);
            bootstrap.handler(new LoggingHandler(LogLevel.ERROR));
            bootstrap.childHandler(channelInitializer);
            channelFuture = bootstrap.bind(port).sync();
            logger.info("Class:{} Server Port:[{}]", this.getClass().getSimpleName(), port);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            System.exit(0);
        }
    }

    public void setChannelInitializer(ChannelInitializer<?> channelInitializer) {
        this.channelInitializer = channelInitializer;
    }

    public void stop() {
        try {
            channelFuture.channel().close().sync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                workerGroup.shutdownGracefully().get();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
            try {
                bossGroup.shutdownGracefully().get();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        logger.info("Class:{} Server 关闭", this.getClass().getSimpleName());
    }

    @Override
    public void destroy() throws Exception {
        stop();
    }
}
